<template>
  <el-card>
    <!-- 头部按钮 -->
    <el-button type="primary" size="default" icon="Plus" @click="addTrademark">
      添加品牌
    </el-button>
    <!-- 表格 -->
    <el-table :data="tableData" style="margin: 10px 0" border>
      <el-table-column type="index" label="序号" width="80" align="center" />
      <el-table-column prop="tmName" label="品牌名称" />
      <el-table-column prop="logoUrl" label="品牌LOGO">
        <template #default="scope">
          <img
            :src="scope.row.logoUrl"
            alt="图片丢失"
            style="width: 64px; height: 64px"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button
            type="primary"
            size="default"
            icon="Edit"
            @click="handleEdit(scope.row)"
          ></el-button>
          <el-popconfirm
            :title="`你确定要删除${scope.row.tmName}吗？`"
            width="200"
            icon="Delete"
            @confirm="handleDeleteConfirm(scope.row.id)"
          >
            <template #reference>
              <el-button
                type="danger"
                size="default"
                icon="Delete"
                @click="handleDelete"
              ></el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[3, 5, 7, 9]"
      :background="true"
      layout="prev, pager, next, jumper, ->, sizes, total"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="getTrademarkList"
    />
  </el-card>
  <!-- 对话框 -->
  <el-dialog
    v-model="dialogFormVisible"
    :title="trademarkParams.id ? '修改品牌' : '添加品牌'"
    width="500"
  >
    <el-form
      ref="formRef"
      style="width: 80%"
      :model="trademarkParams"
      :rules="rules"
    >
      <el-form-item label="品牌名称" prop="tmName" label-width="100">
        <el-input
          v-model="trademarkParams.tmName"
          placeholder="请输入品牌名称"
        />
      </el-form-item>
      <el-form-item label="品牌LOGO" prop="logoUrl" label-width="100">
        <!-- 上传组件 -->
        <el-upload
          class="avatar-uploader"
          action="http://localhost:5173/api/admin/product/fileUpload"
          :show-file-list="false"
          :on-success="handleSuccess"
          :before-upload="beforeUpload"
        >
          <img
            v-if="trademarkParams.logoUrl"
            :src="trademarkParams.logoUrl"
            class="avatar"
          />
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="Trademark">
import { ref, reactive, onMounted, nextTick } from 'vue'
import {
  getTrademarkListApi,
  addOrUpdateTrademarkApi,
  deleteTrademarkApi,
} from '@/api/product/trademark'
import {
  Records,
  Trademark,
  TrademarkResponseData,
} from '@/api/product/trademark/type'
import { ElMessage } from 'element-plus'
import type { UploadProps } from 'element-plus'

const currentPage = ref<number>(1)
const pageSize = ref<number>(3)
const total = ref<number>(0)
const tableData = ref<Records>([])
const dialogFormVisible = ref<boolean>(false)
const trademarkParams = reactive<Trademark>({
  tmName: '',
  logoUrl: 'http://139.198.127.41:9000/sph/20241030/芙莉莲.png',
})
const formRef = ref()

onMounted(() => {
  getTrademarkList()
})

const addTrademark = () => {
  dialogFormVisible.value = true
  trademarkParams.id = 0
  trademarkParams.tmName = ''
  trademarkParams.logoUrl = ''
  nextTick(() => {
    formRef.value.clearValidate()
  })
}

const handleEdit = (row: Trademark) => {
  dialogFormVisible.value = true
  Object.assign(trademarkParams, row)
  nextTick(() => {
    formRef.value.clearValidate()
  })
}

const handleDelete = () => {}

const handleDeleteConfirm = async (id: number) => {
  const res = await deleteTrademarkApi(id)
  if (res.code == 200) {
    ElMessage.success('删除品牌成功')
    getTrademarkList(
      tableData.value.length > 1 ? currentPage.value : currentPage.value - 1,
    )
  } else {
    ElMessage.error('删除品牌失败')
  }
}

const handleSizeChange = () => {
  getTrademarkList()
}

const getTrademarkList = async (pageNo = 1) => {
  currentPage.value = pageNo
  const res: TrademarkResponseData = await getTrademarkListApi(
    currentPage.value,
    pageSize.value,
  )
  if (res.code == 200) {
    total.value = res.data.total
    tableData.value = res.data.records
  }
}

const beforeUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (
    rawFile.type !== 'image/jpeg' &&
    rawFile.type !== 'image/png' &&
    rawFile.type !== 'image/gif'
  ) {
    ElMessage.error('请上传图片（jpg/png/git）')
    return false
  } else if (rawFile.size / 1024 / 1024 > 4) {
    ElMessage.error('图片大小不能超过4MB')
    return false
  }
  return true
}

const handleSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
  trademarkParams.logoUrl = response.data
  formRef.value.clearValidate('logoUrl')
}

const handleCancel = () => {
  dialogFormVisible.value = false
}

const handleConfirm = async () => {
  await formRef.value.validate()
  const res: any = await addOrUpdateTrademarkApi(trademarkParams)
  if (res.code == 200) {
    dialogFormVisible.value = false
    ElMessage.success(`${trademarkParams.id ? '修改' : '添加'}品牌成功`)
    getTrademarkList(trademarkParams.id ? currentPage.value : 1)
  } else {
    dialogFormVisible.value = false
    ElMessage.error(`${trademarkParams.id ? '修改' : '添加'}品牌失败`)
  }
}

const validatorTmName = (rule: any, value: any, callback: any) => {
  if (value.trim().length >= 2) {
    callback()
  } else {
    callback(new Error('品牌名称不少于2个字符'))
  }
}

const validatorLogoUrl = (rule: any, value: any, callback: any) => {
  if (value) {
    callback()
  } else {
    callback(new Error('请上传Logo图片'))
  }
}

const rules = {
  tmName: [
    {
      required: true,
      trigger: 'blur',
      validator: validatorTmName,
    },
  ],
  logoUrl: [
    {
      required: true,
      validator: validatorLogoUrl,
    },
  ],
}
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
